<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    public function add(){
       if(!user_ins()->is_logged_in())
        return ['status'=>0,'mes'=>'login required'];
    
    // 检查是否有title
    if(!rq('title'))
        return ['status'=>0,'msg'=>'request title'];
    $this->title=rq('title');
    $this->user_id=session('user_id');
    if(rq('desc'))
        $this->desc=rq('desc');
    return $this->save() ? 
    ['staus'=>1,'id'=>$this->id]:
    ['staus'=>0,'msg'=>'db insert failed'];
        
    }
    // 更新問題api
    public function change(){
        // 检查用户是否登录
        if(!user_ins()->is_logged_in())
            return ['status'=>0,'msg'=>'login required'];
        //检查传参是否有id
        if(!rq('id'))
            return ['status'=>0,'mes'=>'id is required'];
        $question=$this->find(rq('id'));
        if(!$question)
            return ['status'=>0,'msg'=>'question not ewxists'];
        if($question->user_id!=session('user_id'))
            return ['status'=>0,'msg'=>'permission denied'];
        if(rq('title'))
            $question->title=rq('title');
        if(rq('desc'))
            $question->desc=rq('desc');
        return $question->save()?
        ['status'=>1]:
        ['status'=>0,'msg'=>'db updete failed'];

    }
    // 查看问题api
    public function read(){
        // 检查是否有id
        if(rq('id'))
            return ['status'=>0,'data'=>$this->find(rq('id'))];

        $limit=rq('limit') ?:10;
        $skip=(rq('page') ? rq('page')-1: 0)*$limit;

        $r= $this
            ->orderBy('created_at')
            ->limit($limit)
            ->skip($skip) 
            ->get()
            ->keyBy('id');
        return ['status'=>0,'data'=>$r];
    }
    // 删除问题api
    public function remove(){
         // 检查用户是否登录
        if(!user_ins()->is_logged_in())
            return ['status'=>0,'msg'=>'login required'];
        if(!rq('id'))
            return ['status'=>0,'msg'=>'id is required'];
        $question=$this->find(rq('id'));
        if(!$question) return ['status'=>0,'msg'=>'question not exists'];

        if(session('user_id')!=$question->user_id)
            return ['status'=>0,'msg'=>'permission denied'];
        return $question->delete() ?
        ['status'=>1] :
        ['status'=>0,'msg'=>'db delete  failed'];
    }
}
